package chpt10;

import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class LoginDialog extends JDialog {
	private JTextField usernameTextField;

	public LoginDialog(JFrame parent) {
		// 调用父类的对话框构造方法，true代表模式对话框
		super(parent, "登录对话框", true);
		setLayout(new FlowLayout());

		JLabel usernameLabel = new JLabel("用户名：");
		usernameTextField = new JTextField(10);

		JButton loginButton = new JButton("登录");
		loginButton.addActionListener(event -> {
			String username = usernameTextField.getText();
			if (username.equals("admin")) {
				dispose(); // 释放所占的屏幕资源
				EventQueue.invokeLater(() -> {
					FirstJFrame frame = new FirstJFrame("First JFrame");
					frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
					frame.pack();
					frame.setLocationRelativeTo(null);
					frame.setVisible(true);
				});
			} else {
				// 将LoginDialog.this对话框设为信息框的父窗体
				JOptionPane.showMessageDialog(LoginDialog.this, 
						"用户名错误");
			}
		});
		// 添加组件到对话框
		add(usernameLabel);
		add(usernameTextField);
		add(loginButton);
		// 关闭时释放资源
		this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); 
	}
}